// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// f [author] rhyme_lph
// U [email]  rhymelph@gmail.com
// L [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/http_service/http_user_service.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/page/login/change_password_page.dart';

class ChangePasswordProvider extends BaseProvider {
  TextEditingController passwordController = TextEditingController();
  FocusNode passwordFocusNode = FocusNode();

  bool isNext = false;

  bool passwordError = false;
  bool passwordIncorrect = false;

  bool enable = false;

  @override
  Future get dataFuture => null;

  @override
  void dispose() {
    super.dispose();
    passwordController.dispose();
    passwordFocusNode.dispose();
  }

  @override
  void initState() {
    super.initState();
    final callback = () {
      if (passwordController.text.isNotEmpty) {
        if (enable == false) {
          enable = true;
          update();
        }
      } else {
        if (enable == true) {
          enable = false;
          update();
        }
      }
    };
    passwordController.addListener(callback);
  }

  String oldPassword;

  void onVerify() async {
    passwordError = false;
    passwordIncorrect = false;
    passwordFocusNode.unfocus();
    String password = passwordController.text;
    if (password.length < 6) {
      passwordError = true;
      update();
      return;
    }

    if (isNext == false) {
      if (password != Config.biometricsData.password) {
        passwordIncorrect = true;
        update();
        return;
      }
      isNext = true;
      oldPassword = password;
      passwordController.clear();
      passwordError = false;
      update();
    } else {
      String password = passwordController.text;
      bool isSuccess = false;
      String message;
      await post(HttpUserService.updatePassword(oldPassword, password),
          loadingTip: S.current.loading, onSuccess: (result) {
        isSuccess = true;
      }, onError: (int statusCode, String msg, Object error,
              StackTrace stackTrace) {
        message = msg;
      });
      if (isSuccess == true) {
        obtainContext?.call((context) async {
          await showLoginDetailUpdateSuccessTipBottomSheet(context);
          Navigator.of(context).pop();
          Config.biometricsData = Config.biometricsData..password = password;
          await RProvider.myProvider.updateGlobalMap();
        });
      } else {
        obtainContext?.call((context) async {
          await showGotItTipBottomSheet(context, message);
        });
      }
    }
  }
}
